package com.itic.hpp.login;



import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.itic.appbase.applications.sys.token.persistence.model.Token;
import com.itic.appbase.applications.sys.user.persistence.model.SysUser;
import com.itic.appbase.applications.sys.verifycode.persistence.model.Verifycode;
import com.itic.appbase.applications.sys.verifycode.persistence.model.VerifycodeExample;
import com.itic.appbase.applications.sys.verifycode.persistence.model.VerifycodeExample.Criteria;
import com.itic.appbase.applications.sys.verifycode.service.VerifycodeService;
import com.itic.appbase.framework.annotation.CheckLogin;
import com.itic.appbase.framework.common.constants.DBConst;
import com.itic.appbase.framework.utils.RandomStringHelper;
import com.itic.appbase.framework.utils.StringHelper;
import com.itic.mobile.base.BaseMobile;

@Controller
@RequestMapping(value = "/mobile/login")
public class LoginMobile
     extends BaseMobile {
	
	 @Autowired
	 private VerifycodeService verifycodeService;
	  /**
	    * APP手机发送验证码
	    * @return
	    */
	   @RequestMapping(value="/payCode")
	   @ResponseBody
	   @CheckLogin
	   public Map<String,Object> payCode( HttpServletRequest request,HttpServletResponse response ){
		    Map<String, Object> resultMap = new HashMap<String,Object>();
		   	String errorCode = PARAM_ERROR_CODE;
		   	String errorMsg = PARAM_ERROR_MSG;
		   	try{
		   		SysUser user = this.CurUsersMall(request);
		   		String randomNumStr = RandomStringHelper.randomNumStr(6);
		   		Verifycode phoneCode = new Verifycode();
   				phoneCode.setPhone(user.getMobile());
   				phoneCode.setCode(randomNumStr);
   				phoneCode.setExpiredTime(getExpiredTimeCode(new Date()));
   				String temp = verifycodeService.add(phoneCode);
   				String sendMassage = sendMassagePayCode(user.getMobile(), randomNumStr);
   				if( SUCCESS.equals(temp) && SUCCESS.equals(sendMassage) ){
   					errorCode = SUCCESS_ERROR_CODE;
			       	errorMsg = SUCCESS_ERROR_MSG;
   				}else{
   					errorCode = PHONE_CODE_ERROR_CODE;
			       	errorMsg = PHONE_CODE_ERROR_MSG;
   				}
		   	}catch(Exception e){
		   		errorCode = SERVER_ERROR_CODE;
		       	errorMsg = SERVER_ERROR_MSG;
		   		logException("LoginInterface", "code", e.toString(),"APP手机发送验证码",e);
		   	}
		   	resultMap.put(CODE, errorCode);
		   	resultMap.put(MSG, errorMsg);
		   	isCrrossDomain(response);
		   	return resultMap;
	   }
	   
	   /**
	    * APP手机发送验证码
	    * @return
	    */
	   @RequestMapping(value="/code")
	   @ResponseBody
	   public Map<String,Object> code( HttpServletRequest request,HttpServletResponse response, String phone ){
		    Map<String, Object> resultMap = new HashMap<String,Object>();
		   	String errorCode = PARAM_ERROR_CODE;
		   	String errorMsg = PARAM_ERROR_MSG;
		   	try{
		   		if( StringHelper.isNotBlank(phone) ){
		   		    //发送验证码
	   				String randomNumStr = RandomStringHelper.randomNumStr(6);
	   				
	   				Verifycode phoneCode = new Verifycode();
	   				phoneCode.setPhone(phone);
	   				phoneCode.setCode(randomNumStr);
	   				phoneCode.setExpiredTime(getExpiredTimeCode(new Date()));
	   				
	   				String temp = verifycodeService.add(phoneCode);
	   				String sendMassage = sendMassage(phone, randomNumStr);
	   				  
	   				if( SUCCESS.equals(temp) && SUCCESS.equals(sendMassage) ){
	   					errorCode = SUCCESS_ERROR_CODE;
				       	errorMsg = SUCCESS_ERROR_MSG;
	   				}else{
	   					errorCode = PHONE_CODE_ERROR_CODE;
				       	errorMsg = PHONE_CODE_ERROR_MSG;
	   				}
		   		}
		   	}catch(Exception e){
		   		errorCode = SERVER_ERROR_CODE;
		       	errorMsg = SERVER_ERROR_MSG;
		   		logException("LoginInterface", "code", e.toString(),"APP手机发送验证码",e);
		   	}
		   	resultMap.put(CODE, errorCode);
		   	resultMap.put(MSG, errorMsg);
		   	isCrrossDomain(response);
		   	return resultMap;
	   }
	
	/**
	 * 注册
	 * @param request
	 * @param response
	 */ 
	@RequestMapping(value = "/reg")   
	@ResponseBody 
	public Map<String, Object> reg(HttpServletRequest request,HttpServletResponse response,SysUser user,String code ){  
		 Map<String, Object> resultMap = new HashMap<String,Object>();
	     String errorCode = PARAM_ERROR_CODE;
	   	 String errorMsg = PARAM_ERROR_MSG;
		  try{  
			    //判断参数是否有效
		   		if( StringHelper.isNotBlank(user.getMobile()) && StringHelper.isNotBlank(code) ){
		   			//判断手机号码是否注册过
		   			SysUser usersTemp = sysUserService.getByPhone(user.getMobile());
		   			if( null == usersTemp ){
		   				//验证码是否有效code
		   				if( isEffectiveCode(user.getMobile(),code) ){
				   			sysUserService.add(user);
				   			errorCode = SUCCESS_ERROR_CODE;
					       	errorMsg = SUCCESS_ERROR_MSG;
		   				}else{
					   		errorCode = PHONE_CODE_ERROR_CODE;
					       	errorMsg = PHONE_CODE_ERROR_MSG;
		   				}
		   			}else{
		   		     	//提示用户号码已注册过了
		   				errorCode = PHONE_REGED_ERROR_CODE;
				       	errorMsg = PHONE_REGED_ERROR_MSG;
		   			}
		   	     }
          }catch(Exception e){  
        	  e.printStackTrace();
        	  errorCode = SERVER_ERROR_CODE;
		      errorMsg = SERVER_ERROR_MSG;
        	  logException("LoginMobile", "reg", e.toString(),"注册",e);
          } 
          resultMap.put(CODE, errorCode);
		  resultMap.put(MSG, errorMsg);
		  isCrrossDomain(response);
		  return resultMap;
	}  
		  
	

	/**
	 * 登入
	 * @param request
	 * @param response
	 */ 
	@RequestMapping(value = "/in")   
	@ResponseBody 
	public Map<String, Object> in(HttpServletRequest request,HttpServletResponse response,String phone,String code, String token, String device ){  
		 Map<String, Object> resultMap = new HashMap<String,Object>();
	     String errorCode = PARAM_ERROR_CODE;
	   	 String errorMsg = PARAM_ERROR_MSG;
		  try{  
			   Map<String, Object> dataMap = new HashMap<String,Object>();
			   //用户TOKEN与设备ID登入
			   if( StringHelper.isNotBlank(token) && StringHelper.isNotBlank(device) ){
		   			SysUser user = sysUserService.getUserByTokenAndDevice(token, device);
		   			if( null != user ){
		   				Token tokenObj = tokenService.flushToken(token,device);
		   				dataMap.put("token", tokenObj.getAccessToken());
		   				dataMap.put("expiredTime", tokenObj.getExpiredTime());
		   				resultMap.put(DATA, dataMap);
		   				errorCode = SUCCESS_ERROR_CODE;
				       	errorMsg = SUCCESS_ERROR_MSG;
		   			}else{
		   				errorCode = LOGIN_ERROR_CODE;
				       	errorMsg = LOGIN_ERROR_MSG;
		   			}
		   	   }
			   //用户phone与code登入
			   if( StringHelper.isNotBlank(phone) && StringHelper.isNotBlank(code) && StringHelper.isNotBlank(device) ){
				   if( isEffectiveCode(phone,code) ){
					    SysUser user = sysUserService.getByPhone(phone);
			   		    if( null == user ){//注册用户
			   		    	user=sysUserService.reg(phone);
			   		    }
			   		    //生成token信息
				   		Token tokenObj = tokenService.getTokenByPhoneAndDevice(user,device);
		   				dataMap.put("token", tokenObj.getAccessToken());
		   				dataMap.put("expiredTime", tokenObj.getExpiredTime());
		   				resultMap.put(DATA, dataMap);
		   				errorCode = SUCCESS_ERROR_CODE;
				       	errorMsg = SUCCESS_ERROR_MSG;
				   }else{
					   errorCode = PHONE_CODE_ERROR_CODE;
				       errorMsg = PHONE_CODE_ERROR_MSG;
				   }
			   }
          }catch(Exception e){  
        	  e.printStackTrace();
        	  errorCode = SERVER_ERROR_CODE;
		      errorMsg = SERVER_ERROR_MSG;
        	  logException("LoginMobile", "in", e.toString(),"登入",e);
          } 
          resultMap.put(CODE, errorCode);
		  resultMap.put(MSG, errorMsg);
		  isCrrossDomain(response);
		  return resultMap;
	}  
	
	
	 /**
	   * 验证码是否有效
	   * @param phone
	   * @param code
	   * @return
	   */
	  public boolean isEffectiveCode( String phone, String code ){
	    	boolean result = false;
	    	VerifycodeExample example = new VerifycodeExample();
	    	Criteria criteria = example.createCriteria();
	    	criteria.andIsEffectiveEqualTo(DBConst.TRUE);
	    	criteria.andCodeEqualTo(code);
	    	criteria.andPhoneEqualTo(phone);
	    	criteria.andExpiredTimeGreaterThanOrEqualTo(new Date());
	    	
	    	List<Verifycode> list = verifycodeService.list(example);
	    	if( list.size() > 0 ){
	    		result = true;
	    	}
	    	return result;
	  }
}